/****************************************************
 * 
 * home soft 版权所有.
 * 
 *****************************************************/

package com.homesoft.runtime.core;

import com.homesoft.runtime.config.Configuration;
import com.homesoft.runtime.config.ConfigurationManager;
import com.homesoft.runtime.config.ListenerConfigSection;
import com.homesoft.runtime.core.loaders.BusinessClassLoader;
import com.homesoft.runtime.log.ILog;
import com.homesoft.runtime.log.LogLevel;
import com.homesoft.runtime.log.LogManager;

/**
 * @author lihg
 * @data 2012-9-12
 */
public class RuntimeInstance implements IRuntimeInstance {

	private RuntimeListenerManager _listenerManager;
	private final String LISTENER = "listener";
	private final String DEFAULT_CONFIG_DIRECTORY = "config";
	private static ILog logger = LogManager.getLogger(RuntimeInstance.class);

	private boolean _isDisposed;

	@Override
	public void dispose() {
		if (!_isDisposed) {
			stop();
			_isDisposed = true;
		}
	}

	@Override
	public void start() {
		long groupId = logger.beginWriteTraceLog(LogLevel.Info, "Runtime开始启动");
		try {
			PrepareRuntimeListener();
			BusinessClassLoader.Init();
			_listenerManager.startListener();
		} finally {
			logger.endWriteTraceLog(groupId, LogLevel.Info, "Runtime启动完成");
		}
	}

	/**
	 * 
	 */
	private void PrepareRuntimeListener() {
		long beginLogId = logger.beginWriteTraceLog(LogLevel.Info, "开始注册所有监听器");
		try {
			_listenerManager.clearListeners();
			// 注册内置监听器
			RegisterInternalListener();

			Configuration config = ConfigurationManager.getConfiguration();
			boolean isExist = config.isExistSection(LISTENER);
			if (!isExist) {
				logger.writeTraceLog(LogLevel.Info, "没有配置LISTENER信息 模块名称：" + LISTENER);
				// throw new
				// GTPConfigurationException(ConfigurationErrorCode.NOT_FOUND_LISTENER_CONFIG,
				// LISTENER);
			}
			ListenerConfigSection listener = null;// config.<ListenerConfigSection>getSection();
			// foreach (ListenerConfigSection.Handler handler :
			// listener.getHandlers())
			// {
			// RegisterRuntimeListener(handler.TypeName, true);
			RegisterRuntimeListener("", true);
			// }
		} finally {
			logger.endWriteTraceLog(beginLogId, LogLevel.Info, "注册所有监听器完成");
		}

	}

	/**
	 * @param string
	 * @param b
	 */
	private void RegisterRuntimeListener(String listenerClass, boolean throwOnError) {
		Class clazz = null;//TODO: RuntimeResolver.ResolveRuntimeType(listenerClass, throwOnError);
		if (clazz == null) {
			logger.writeSystemLog(LogLevel.Error, String.format("未找到类型为[{0}]的监听器", listenerClass));
			logger.writeTraceLog(LogLevel.Error, String.format("未找到类型为[{0}]的监听器", listenerClass));
			return;
		}

		IRuntimeListener listener = null;

		try {
			listener = (IRuntimeListener) clazz.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// Activator.CreateInstance(clazz)
		//listener.setRuntimeInstance(this);

		_listenerManager.registerListener(listener);
		logger.writeSystemLog(LogLevel.Info, String.format("注册监听器成功: [{0}]", listenerClass));
		logger.writeTraceLog(LogLevel.Info, String.format("注册监听器成功: [{0}]", listenerClass));
	}

	/**
	 * 
	 */
	private void RegisterInternalListener() {
		// RegisterRuntimeListener(RuntimeResolver.CreateQualifiedName(typeof(SystemStartupListener)),
		// true);
		RegisterRuntimeListener("GTP.Runtime.Core.Databases.DatabaseStartupListener, GTP.Runtime.Core", true);
		RegisterRuntimeListener("GTP.Runtime.Metadata.MetadataEngineStartupListener, GTP.Runtime.Metadata", true);
		RegisterRuntimeListener("GTP.Runtime.NamedSql.NamedSqlListener, GTP.Runtime.DataService", true);
		RegisterRuntimeListener("GTP.Runtime.EntityService.EntityServiceListener, GTP.Runtime.EntityService", true);
		RegisterRuntimeListener("GTP.Runtime.Biz.ServiceStartupListener, GTP.Runtime.Biz", true);
		RegisterRuntimeListener("GTP.Runtime.Biz.Event.EventStartupListener, GTP.Runtime.Biz", true);
		RegisterRuntimeListener("GTP.Runtime.WebUI.WebUIStartupListener, GTP.Runtime.WebUI", true);
	}

	@Override
	public void stop() {
		long beginLogId = logger.beginWriteTraceLog(LogLevel.Info, "Runtime开始关闭");
		try {
			// TODO:BusinessClassLoader.Clear();
			_listenerManager.stopListener();
		} catch (Exception ex) {
			logger.writeTraceLog(LogLevel.Error, "关闭运行时环境时出错:" + ex.getMessage());
		}
		logger.endWriteTraceLog(beginLogId, LogLevel.Info, "Runtime关闭完成");
	}
}
